﻿using HandyControl.Controls;
using HandyControl.Interactivity;
using Microsoft.Win32;
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace LpbPrj.Client.Controls;

public class ImageSourceSelector : ImageSelector
{
    public ImageSourceSelector()
    {
        CommandBindings.Add(new CommandBinding(ControlCommands.Selected, SelectedImage));
        SetCurrentValue(FilterProperty, "(.png)|*.png|(.jpg)|*.jpg");
        SetCurrentValue(DefaultExtProperty, ".png");
    }

    private void SelectedImage(object sender, ExecutedRoutedEventArgs e)
    {
        //if (!HasValue)
        {
            var dialog = new OpenFileDialog
            {
                RestoreDirectory = true,
                Filter = Filter,
                DefaultExt = DefaultExt
            };

            if (dialog.ShowDialog() == true)
            {
                SetCurrentValue(SourceProperty, BitmapFrame.Create(new Uri(dialog.FileName, UriKind.RelativeOrAbsolute)));
            }
        }
        //else
        //{
        //    SetCurrentValue(SourceProperty, default);
        //}
    }


    public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
        nameof(Source), typeof(ImageSource), typeof(ImageSourceSelector), new FrameworkPropertyMetadata(default(ImageSource), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSourceChangedCallback));
    private static void OnSourceChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d == null) return;
        ImageSourceSelector edit = (ImageSourceSelector)d;
        if (edit == null) return;

        if (e.NewValue is ImageSource imageSource)
        {
            edit.SetValue(UriPropertyKey, new Uri(imageSource.ToString(), UriKind.RelativeOrAbsolute));
            edit.SetValue(PreviewBrushPropertyKey, new ImageBrush(BitmapFrame.Create(new Uri(imageSource.ToString(), UriKind.RelativeOrAbsolute))) { Stretch = edit.Stretch });
            edit.SetValue(HasValuePropertyKey, true);
            edit.SetCurrentValue(ToolTipProperty, imageSource.ToString());

            edit.RaiseEvent(new RoutedEventArgs(ImageSelectedEvent, edit));
        }
        else
        {
            edit.SetValue(UriPropertyKey, default);
            edit.SetValue(PreviewBrushPropertyKey, default);
            edit.SetValue(HasValuePropertyKey, false);
            edit.SetCurrentValue(ToolTipProperty, default);

            edit.RaiseEvent(new RoutedEventArgs(ImageSelectedEvent, edit));
        }
    }
    public ImageSource Source
    {
        get => (ImageSource)GetValue(SourceProperty);
        set => SetValue(SourceProperty, value);
    }

}
